import 'package:async/async.dart';
import 'package:boss/models/necessary_order.dart';
import 'package:boss/provider/necessary_order_provider.dart';
import 'package:boss/ui/widget/loader/empty_widget.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'necessary_order_item.dart';

class NecessaryOrderList extends StatelessWidget {
  Future<Result<List<NecessaryOrder>>> _loadTask(BuildContext context) async {
    var necessaryOrderProvider = Provider.of<NecessaryOrderProvider>(
      context,
      listen: false,
    );

    return necessaryOrderProvider.initData();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Loader<List<NecessaryOrder>>(
        loadTask: () => _loadTask(context),
        builder: (context) {
          return Consumer<NecessaryOrderProvider>(
            builder: (context, necessaryOrderProvider, _) {
              if (necessaryOrderProvider.necessaryOrders.length == 0) return EmptyWidget();

              return ListView.builder(
                padding: EdgeInsets.symmetric(
                  horizontal: 30.w,
                ),
                itemBuilder: (context, index) {
                  var current = necessaryOrderProvider.necessaryOrders[index];

                  return NecessaryOrderItem(
                    data: current,
                    onTap: () {
                      necessaryOrderProvider.changeUseStatus(current);
                    },
                    onEdit: () {
                      Navigator.pushNamed(context, '/necessaryOrderDetailPage', arguments: {
                        'data': NecessaryOrder.fromJson(current.toJson()),
                      });
                    },
                  );
                },
                itemCount: necessaryOrderProvider.necessaryOrders.length,
              );
            },
          );
        },
      ),
    );
  }
}
